package org.example.service.impl;

import com.github.pagehelper.PageHelper;
import org.example.dao.DeptDao;
import org.example.domain.Dept;
import org.example.domain.PageBean;
import org.example.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Jimmy
 * @version 1.0
 */
@Transactional(rollbackFor = RuntimeException.class)
@Service("deptService")
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptDao deptDao;

    @Override
    public PageBean<Dept> findByPage(Dept dept,int pagenum, int pagesize) {
        int total = deptDao.findTotal(dept);
        if (total<pagesize){
            pagesize = total;
        }
        List<Dept> depts;
        if (pagenum == 0 && pagesize == 0){
            depts = deptDao.findByPage(dept);
        }else {
            PageHelper.startPage(pagenum,pagesize);
            depts = deptDao.findByPage(dept);
        }
        if (dept.getDeptId() != null || dept.getDeptname() != null || dept.getPid() != null){
            return new PageBean<>(total,pagenum,depts);
        }
        List<Dept> deptTree = new ArrayList<>();
        for (Dept d : depts) {
            if (d.getPid() == null){
                deptTree.add(d);
            }
        }
        depts.removeAll(deptTree);
        for (Dept deptParent : deptTree) {
            List<Dept> deptChildren = new ArrayList<>();
            for (Dept d : depts) {
                if (deptParent.getDeptId().equals(d.getPid())){
                    deptChildren.add(d);
                }
            }
            depts.removeAll(deptChildren);
            deptParent.setChildren(deptChildren);
            for (Dept deptChild : deptChildren) {
                List<Dept> deptGrandson = new ArrayList<>();
                for (Dept d : depts) {
                    if (deptChild.getDeptId().equals(d.getPid())){
                        deptGrandson.add(d);
                    }
                }
                deptChild.setChildren(deptGrandson);
            }
        }

        return new PageBean<>(total,pagenum,deptTree);
    }

    @Override
    public int addDept(Dept dept) {
        return deptDao.addDept(dept);
    }

    @Override
    public Dept findById(String deptId) {
        return deptDao.findById(deptId);
    }

    @Override
    public int update(Dept dept) {
        return deptDao.update(dept);
    }

    @Override
    public int delete(String deptId) {
        return deptDao.delete(deptId);
    }
}
